#!/usr/bin/env python
import os
import urllib
import datetime
import urlparse
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
#use_library('django', '1.2')
from google.appengine.api import images
from google.appengine.ext.webapp import template
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson as json
from google.appengine.ext.webapp import util

import DataModels
class Explorer(webapp.RequestHandler):
    def get(self,directory_key=None):
        #try:
            u = DataModels.DataUser.get_current_user()
            if directory_key == None:
                d = DataModels.Directory.all().ancestor(u).filter('name', '/').fetch(1)[0]
            else:
                d = DataModels.Directory.all().ancestor(u).get(db.Key(directory_key))
            template_values = { 'page_title' : 'Directory ' + d.name,
                               'user_nickname' : u.user.nickname(),
                               'directory' : d,
                               'directories' : d.directories,
                               'files' : d.files.filter('deleted', False)
                               }
            path = os.path.join(os.path.dirname(__file__), 'templates/Explorer.html')
            self.response.out.write(template.render(path, template_values))
        #except:
        #    path = os.path.join(os.path.dirname(__file__), 'templates/Exception.html')
        #    self.response.out.write(template.render(path, {}))

class json_files_info(blobstore_handlers.BlobstoreUploadHandler):
    def get(self, file_key=None):
        self.response.headers.add_header("Access-Control-Allow-Origin","*")
        if file_key != None:
            f = DataModels.File.get(db.Key(file_key))
            thumbnail = '/static/thumbnails/' + f.blob_info.content_type + '.png';
            self.response.headers.add_header("Access-Control-Allow-Origin","*")
            self.response.out.write(json.dumps({'key' : unicode(f.key()),
                                                    'name' : unicode(f.name),
                                                    'description' : unicode(f.description),
                                                    'thumbnail' : thumbnail,
                                                    'size' : f.blob_info.size,
                                                    'modification' : unicode(f.blob_info.creation),
                                                    'content_type' : unicode(f.blob_info.content_type)
                                                    }))
class json_files_upload(blobstore_handlers.BlobstoreUploadHandler):
	def get(self):
		upload_url = blobstore.create_upload_url('/json/files/upload')
		self.response.headers.add_header("Access-Control-Allow-Origin","*")
		self.response.out.write(json.dumps({'url' : upload_url}))
	def post(self):
		self.response.headers.add_header("Access-Control-Allow-Origin","*")
		try:
			u = DataModels.DataUser.get_current_user()
			d = DataModels.Directory.all().ancestor(u).filter('__key__', db.Key(self.request.get('directory'))).fetch(1)[0]
		except:            
			d = DataModels.Directory.all().filter('__key__', db.Key(self.request.get('directory'))).fetch(1)[0]
			#TODO: Implement password filter
		for file in self.get_uploads():
			try:
				f = DataModels.File(parent = d,
                                    directory = d,
                                    name = blobstore.BlobInfo(file.key()).filename,
                                    blob_info = file.key(),
                                    thumbnail = '')
				f.put()
			finally:
				self.redirect("/json/files/info/%s" % f.key())

class json_files_delete(webapp.RequestHandler):
    def get(self, status):
        if status == 'True':
            self.response.out.write('{ \'deleted\' : true}')
        else:
            self.response.out.write('{ \'deleted\' : false}')

    def post(self):
        try:
            u = DataModels.DataUser.get_current_user()
            keys = str(self.request.get('keys')).split(',')
            for key in keys:
                f = DataModels.File.all().ancestor(u).filter('__key__', db.Key(key)).fetch(1)[0]
                f.deleted = True
                f.put()
            self.redirect('/json/files/delete/True')
        except:
            self.redirect('/json/files/delete/False')

class json_directory_list(webapp.RequestHandler):
	def get(self, directory_key):
		try:
			u = DataModels.DataUser.get_current_user()
			f = DataModels.File.all().ancestor(db.Key(directory_key)).ancestor(u)
		except:
			f = DataModels.File.all().ancestor(db.Key(directory_key))
			#TODO: implement password protection
        
		self.response.headers.add_header("Access-Control-Allow-Origin","*")
		self.response.out.write('{')
		i=0

		for file in f:
			i = i+1
			thumbnail = '/static/thumbnails/' + file.blob_info.content_type + '.png';
			if i > 1:
				self.response.out.write(', ')
			self.response.out.write(' "' + str(i) + '" : {')
			self.response.out.write('"filekey" : "' + str(file.key()) + '", ')
			self.response.out.write('"filename" : "' + file.name + '", ')
			self.response.out.write('"modification" : "' + unicode(file.blob_info.creation) + '", ')
			self.response.out.write('"size" : "' + unicode(file.blob_info.size) + '", ')
			self.response.out.write('"content_type" : "' + unicode(file.blob_info.content_type) + '", ')
			self.response.out.write('"thumbnail" : "' + thumbnail + '" ')
			self.response.out.write('}')
		self.response.out.write(' }')
	        
def main():
    application = webapp.WSGIApplication([
                                            ('/Explorer/([^/]+)?', Explorer),
                                            ('/json/files/delete/([^/]+)?', json_files_delete),
                                            ('/json/files/delete', json_files_delete),
                                            ('/json/files/info/([^/]+)?', json_files_info),
                                            ('/json/files/upload', json_files_upload),
                                            #('/json/directory/create', json_directory_create),
                                            #('/json/directory/([^/]+)?/delete', json_directory_delete),
                                            ('/json/directory/([^/]+)?/list', json_directory_list)
                                         ],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
